// 全局变量
let websocket = null;
let currentUser = null;
let onlineUsers = new Set();
let selectedUser = null;

// DOM 元素
const loginPage = document.getElementById('loginPage');
const chatPage = document.getElementById('chatPage');
const loginForm = document.getElementById('loginForm');
const currentUserElement = document.getElementById('currentUser');
const onlineUsersList = document.getElementById('onlineUsersList');
const chatMessages = document.getElementById('chatMessages');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
const targetUserSelect = document.getElementById('targetUser');
const connectionStatus = document.getElementById('connectionStatus');
const logoutBtn = document.getElementById('logoutBtn');
const loadingOverlay = document.getElementById('loadingOverlay');
const messageToast = document.getElementById('messageToast');
const toastMessage = document.getElementById('toastMessage');

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    checkLoginStatus();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 登录表单提交
    loginForm.addEventListener('submit', handleLogin);
    
    // 消息发送
    sendBtn.addEventListener('click', sendMessage);
    messageInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });
    
    // 消息输入字符计数
    messageInput.addEventListener('input', updateCharCount);
    
    // 目标用户选择
    targetUserSelect.addEventListener('change', function() {
        selectedUser = this.value;
        updateSendButton();
    });
    
    // 退出登录
    logoutBtn.addEventListener('click', handleLogout);
    
    // 用户列表点击
    onlineUsersList.addEventListener('click', function(e) {
        const userItem = e.target.closest('.user-item');
        if (userItem) {
            const username = userItem.dataset.username;
            if (username && username !== currentUser) {
                selectUser(username);
            }
        }
    });
}

// 检查登录状态
function checkLoginStatus() {
    // 这里可以添加检查本地存储的登录状态
    // 如果已登录，直接进入聊天页面
}

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const formData = new FormData(loginForm);
    const username = formData.get('username').trim();
    const password = formData.get('password');
    
    if (!username) {
        showToast('请输入用户名', 'error');
        return;
    }
    
    if (!password) {
        showToast('请输入密码', 'error');
        return;
    }
    
    showLoading(true);
    
    try {
        const response = await fetch('/user/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `userName=${encodeURIComponent(username)}&passWord=${encodeURIComponent(password)}`
        });
        
        const result = await response.json();
        
        if (result.flag) {
            currentUser = username;
            showLoading(false);
            showToast('登录成功！', 'success');
            setTimeout(() => {
                showChatPage();
                connectWebSocket();
            }, 1000);
        } else {
            showLoading(false);
            showToast(result.message || '登录失败', 'error');
        }
    } catch (error) {
        showLoading(false);
        showToast('网络错误，请重试', 'error');
        console.error('Login error:', error);
    }
}

// 显示聊天页面
function showChatPage() {
    loginPage.classList.add('hidden');
    chatPage.classList.remove('hidden');
    currentUserElement.textContent = currentUser;
}

// 连接WebSocket
function connectWebSocket() {
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/chat`;
    
    try {
        websocket = new WebSocket(wsUrl);
        
        websocket.onopen = function() {
            updateConnectionStatus('connected', '已连接');
            showToast('WebSocket连接成功', 'success');
        };
        
        websocket.onmessage = function(event) {
            handleWebSocketMessage(event.data);
        };
        
        websocket.onclose = function() {
            updateConnectionStatus('disconnected', '连接断开');
            showToast('连接已断开，正在尝试重连...', 'warning');
            // 尝试重连
            setTimeout(() => {
                if (websocket.readyState === WebSocket.CLOSED) {
                    connectWebSocket();
                }
            }, 3000);
        };
        
        websocket.onerror = function(error) {
            updateConnectionStatus('disconnected', '连接错误');
            showToast('WebSocket连接错误', 'error');
            console.error('WebSocket error:', error);
        };
        
    } catch (error) {
        updateConnectionStatus('disconnected', '连接失败');
        showToast('无法连接到服务器', 'error');
        console.error('WebSocket connection error:', error);
    }
}

// 处理WebSocket消息
function handleWebSocketMessage(data) {
    try {
        const message = JSON.parse(data);
        
        if (message.system) {
            // 系统消息 - 更新在线用户列表
            if (Array.isArray(message.message)) {
                updateOnlineUsers(message.message);
            } else if (typeof message.message === 'string') {
                // 用户上线/下线消息
                addSystemMessage(message.message);
            }
        } else {
            // 聊天消息
            addChatMessage(message.fromName, message.message, false);
        }
    } catch (error) {
        console.error('Error parsing WebSocket message:', error);
    }
}

// 更新在线用户列表
function updateOnlineUsers(users) {
    onlineUsers.clear();
    onlineUsersList.innerHTML = '';
    targetUserSelect.innerHTML = '<option value="">选择聊天对象</option>';
    
    users.forEach(username => {
        if (username !== currentUser) {
            onlineUsers.add(username);
            
            // 添加到侧边栏用户列表
            const userItem = document.createElement('div');
            userItem.className = 'user-item';
            userItem.dataset.username = username;
            userItem.innerHTML = `
                <div class="avatar">
                    <i class="fas fa-user"></i>
                </div>
                <div class="username">${username}</div>
            `;
            onlineUsersList.appendChild(userItem);
            
            // 添加到选择框
            const option = document.createElement('option');
            option.value = username;
            option.textContent = username;
            targetUserSelect.appendChild(option);
        }
    });
    
    updateSendButton();
}

// 选择用户
function selectUser(username) {
    selectedUser = username;
    targetUserSelect.value = username;
    
    // 更新UI选中状态
    document.querySelectorAll('.user-item').forEach(item => {
        item.classList.remove('selected');
        if (item.dataset.username === username) {
            item.classList.add('selected');
        }
    });
    
    updateSendButton();
}

// 发送消息
function sendMessage() {
    if (!websocket || websocket.readyState !== WebSocket.OPEN) {
        showToast('连接未建立，无法发送消息', 'error');
        return;
    }
    
    if (!selectedUser) {
        showToast('请选择聊天对象', 'warning');
        return;
    }
    
    const messageText = messageInput.value.trim();
    if (!messageText) {
        showToast('请输入消息内容', 'warning');
        return;
    }
    
    // 发送消息到服务器
    const message = {
        toName: selectedUser,
        message: messageText
    };
    
    websocket.send(JSON.stringify(message));
    
    // 在本地显示消息
    addChatMessage(currentUser, messageText, true);
    
    // 清空输入框
    messageInput.value = '';
    updateCharCount();
    updateSendButton();
}

// 添加聊天消息到界面
function addChatMessage(fromName, messageText, isOwn) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${isOwn ? 'own' : ''}`;
    
    const now = new Date();
    const timeString = now.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
    });
    
    messageDiv.innerHTML = `
        <div class="message-avatar">
            <i class="fas fa-user"></i>
        </div>
        <div class="message-content">
            <p class="message-text">${escapeHtml(messageText)}</p>
            <div class="message-time">${timeString}</div>
        </div>
    `;
    
    chatMessages.appendChild(messageDiv);
    scrollToBottom();
}

// 添加系统消息
function addSystemMessage(message) {
    const systemDiv = document.createElement('div');
    systemDiv.className = 'system-message';
    systemDiv.textContent = message;
    
    chatMessages.appendChild(systemDiv);
    scrollToBottom();
}

// 更新连接状态
function updateConnectionStatus(status, text) {
    connectionStatus.className = `status-indicator ${status}`;
    connectionStatus.innerHTML = `<i class="fas fa-circle"></i> ${text}`;
}

// 更新发送按钮状态
function updateSendButton() {
    const hasMessage = messageInput.value.trim().length > 0;
    const hasTarget = selectedUser && selectedUser !== '';
    const isConnected = websocket && websocket.readyState === WebSocket.OPEN;
    
    sendBtn.disabled = !(hasMessage && hasTarget && isConnected);
}

// 更新字符计数
function updateCharCount() {
    const count = messageInput.value.length;
    const charCount = document.querySelector('.char-count');
    charCount.textContent = `${count}/500`;
    
    if (count > 450) {
        charCount.style.color = '#ef4444';
    } else if (count > 400) {
        charCount.style.color = '#f59e0b';
    } else {
        charCount.style.color = '#999';
    }
    
    updateSendButton();
}

// 滚动到底部
function scrollToBottom() {
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 显示加载动画
function showLoading(show) {
    if (show) {
        loadingOverlay.classList.remove('hidden');
    } else {
        loadingOverlay.classList.add('hidden');
    }
}

// 显示提示消息
function showToast(message, type = 'info') {
    toastMessage.textContent = message;
    messageToast.className = `toast ${type}`;
    messageToast.classList.remove('hidden');
    
    setTimeout(() => {
        messageToast.classList.add('hidden');
    }, 3000);
}

// 处理退出登录
function handleLogout() {
    if (websocket) {
        websocket.close();
    }
    
    currentUser = null;
    onlineUsers.clear();
    selectedUser = null;
    
    // 清空界面
    chatMessages.innerHTML = `
        <div class="welcome-message">
            <i class="fas fa-rocket"></i>
            <p>欢迎来到聊天室！开始与朋友们聊天吧！</p>
        </div>
    `;
    onlineUsersList.innerHTML = '';
    targetUserSelect.innerHTML = '<option value="">选择聊天对象</option>';
    messageInput.value = '';
    
    // 返回登录页面
    chatPage.classList.add('hidden');
    loginPage.classList.remove('hidden');
    loginForm.reset();
    
    showToast('已退出登录', 'info');
}

// HTML转义函数
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 页面卸载时关闭WebSocket连接
window.addEventListener('beforeunload', function() {
    if (websocket) {
        websocket.close();
    }
});

// 处理页面可见性变化
document.addEventListener('visibilitychange', function() {
    if (document.hidden) {
        // 页面隐藏时暂停某些操作
    } else {
        // 页面显示时恢复操作
        if (websocket && websocket.readyState === WebSocket.CLOSED) {
            connectWebSocket();
        }
    }
});
